package com.ljy.my_study.java.thread;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TestMain2 {

    //两个线程轮流打印数字，从0~10
    public static void main(String[] args) {
        ReentrantLock lock=new ReentrantLock();
        Condition condition1=lock.newCondition();
        Condition condition2=lock.newCondition();
        AtomicInteger a=new AtomicInteger(1);
        Runnable runnable1=()->{
            while(a.get()<=10){
                try{
                    lock.lock();
                    if(a.get()%2!=0){
                        condition2.signal();
                        condition1.await();
                    }
                    System.out.println(Thread.currentThread().getName()+"-"+a.get());
                    a.incrementAndGet();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        };
        Runnable runnable2=()->{
            while(a.get()<=10){
                try{
                    lock.lock();
                    if(a.get()%2==0){
                        condition1.signal();
                        condition2.await();
                    }
                    System.out.println(Thread.currentThread().getName()+"-"+a.get());
                    a.incrementAndGet();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        };
        Thread t1=new Thread(runnable1);
        t1.setName("thread1");
        Thread t2=new Thread(runnable2);
        t2.setName("thread2");
        t1.start();
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }
}
